package com.cskaoyan.processor;

import com.cskaoyan.bean.Animal;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author stone
 * @date 2022/12/20 16:24
 */
@Component
public class AnimalBeanPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        // 狸猫换太子
        // 通过委托类对象bean生成代理对象proxy，return proxy
        if (bean instanceof Animal) {
            InvocationHandler invocationHandler = new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    if ("toString".equals(method.getName())) {
                        return method.invoke(bean, args);
                    }
                    System.out.println("hello");
                    Object invoke = method.invoke(bean, args);
                    System.out.println("world");
                    return invoke;
                }
            };
            Object proxy = Proxy.newProxyInstance(bean.getClass().getClassLoader(), bean.getClass().getInterfaces(), invocationHandler);
            return proxy;
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }
}
